package com.seres.feign.converter;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.exc.InvalidDefinitionException;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.lang.Nullable;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class CustomMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

    public CustomMappingJackson2HttpMessageConverter() {
        // 先将原先支持的MediaType列表拷出
        List<MediaType> mediaTypeList = new ArrayList<>(this.getSupportedMediaTypes());
        //加入对text/plain的支持
        mediaTypeList.add(new MediaType("text", "plain", StandardCharsets.UTF_8));
        //将已经加入了text/json的MediaType支持列表设置为其支持的媒体类型列表
        this.setSupportedMediaTypes(mediaTypeList);
    }

    /**
     * 自定义解析
     * @param type
     * @param contextClass
     * @param inputMessage
     * @return
     * @throws IOException
     * @throws HttpMessageNotReadableException
     */
    @Override
    public Object read(Type type, @Nullable Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        try {
            return JSONObject.parseObject(IOUtils.toString(inputMessage.getBody()),type);
        } catch (InvalidDefinitionException var4) {
            throw new HttpMessageConversionException("Type definition error: " + var4.getType(), var4);
        } catch (JsonProcessingException var5) {
            throw new HttpMessageNotReadableException("JSON parse error: " + var5.getOriginalMessage(), var5, inputMessage);
        }
    }
}
